<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="结算时间" name="createTime">
						<a-range-picker v-model:value="searchFormState.createTime" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
					</a-form-item>
				</a-col>
				<a-col :span="12">
					<a-button type="default" @click="setDate('0')">今日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('1')">昨日</a-button>
					<a-button style="margin: 0 1px" @click="setDate('2')">本周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('3')">上周</a-button>
					<a-button style="margin: 0 1px" @click="setDate('4')">本月</a-button>
					<a-button style="margin: 0 1px" @click="setDate('5')">上月</a-button>
				</a-col>
				<a-col :span="6" style="align-items: end">
					<a-checkbox v-model:checked="searchFormState.isHavingByType" @change="changeIsTotal" style="padding-right:15px ">汇总</a-checkbox>
					<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'"/>
					</a>
				</a-col>
			</a-row>
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="结算门店" name="businessShippingStoreId">
						<xn-page-select
							ref="xnsettlementStoreIdPageSelectRef"
							v-model:value="searchFormState.businessShippingStoreId"
							placeholder="请选择结算门店"
							allow-clear
							show-search
							:page-function="settlementStoreIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6" >
					<a-form-item label="收（付）款账户" name="businessAccountId">
						<xn-page-select
							ref="xnsettlementAccountIdPageSelectRef"
							v-model:value="searchFormState.businessAccountId"
							placeholder="请选择收（付）款账户"
							allow-clear
							show-search
							:page-function="settlementAccountIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="结算类型" name="businessSettlementType">
						<a-select v-model:value="searchFormState.businessSettlementType"
								  @change="businessSettlementTypeChange"
								  placeholder="请选择结算类型" :options="settlementTypeOptions" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="结算项目" name="businessProjectId">
						<xn-page-select
							ref="xnsettlementProjectIdPageSelectRef"
							v-model:value="searchFormState.businessProjectId"
							placeholder="请选择结算项目"
							allow-clear
							show-search
							:page-function="settlementProjectIdSelector"
							@change="projectIdChange"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="结算单号" name="businessCode">
						<a-input v-model:value="searchFormState.businessCode" placeholder="请输入结算单号" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="业务单号" name="businessBusinessId">
						<a-input v-model:value="searchFormState.businessBusinessId" placeholder="请输入业务单号" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="结算对象" name="businessObjectId">
						<xn-page-select
							ref="xnsettlementObjectIdPageSelectRef"
							v-model:value="searchFormState.businessObjectId"
							placeholder="请选择结算对象"
							allow-clear
							show-search
							:page-function="settlementObjectIdSelector"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6" v-show="advanced">
					<a-form-item label="单据状态" name="businessStatus">
						<a-select v-model:value="searchFormState.businessStatus"
								  placeholder="请选择单据状态" :options="settlementStatusOptions" allow-clear/>
					</a-form-item>
				</a-col>
				<a-col :span="2" v-show="searchFormState.isHavingByType">
					汇总选项：
				</a-col>
				<a-col :span="3" v-show="searchFormState.isHavingByType">
					<a-checkbox v-model:checked="searchFormState.isHavingByStore" @change="changeTotalOption('isHavingByStore')">按门店汇总</a-checkbox>
				</a-col>
				<a-col :span="3" v-show="searchFormState.isHavingByType">
					<a-checkbox v-model:checked="searchFormState.isHavingByAccount" @change="changeTotalOption('isHavingByAccount')">按结算账户汇总</a-checkbox>
				</a-col>
				<a-col :span="3" v-show="searchFormState.isHavingByType">
					<a-checkbox v-model:checked="searchFormState.isHavingByProject" @change="changeTotalOption('isHavingByProject')">按结算项目汇总</a-checkbox>
				</a-col>
				<a-col :span="3" v-show="searchFormState.isHavingByType">
					<a-checkbox v-model:checked="searchFormState.isHavingByObject" @change="changeTotalOption('isHavingByObject')">按结算对象汇总</a-checkbox>
				</a-col>

			</a-row>
		</a-form>
		<s-table
			ref="tableRef"
			:columns="columns"
			:data="loadData"
			:alert="options.alert.show"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
		>
			<template #operator class="table-operator">
				<a-space>
					<a-button type="primary" @click="formRef.onOpen()" v-if="hasPerm('supplierFinanceSettlementAdd')" >
						<template #icon>
							<plus-outlined/>
						</template>
						新增
					</a-button>
					<a-button @click="exportBatchSettlement" v-if="hasPerm('supplierFinanceSettlementExport')">
						<template #icon>
							<export-outlined/>
						</template>
						批量导出
					</a-button>
				</a-space>
			</template>
			<template #bodyCell="{ column, record }">
				<template v-if="column.dataIndex === 'businessSettlementType'">
					<a-tag v-if="record.businessSettlementType === '0'" color="red">
						收入
					</a-tag>
					<a-tag v-if="record.businessSettlementType === '1'" color="green">
						支出
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'businessStatus'">
					<a-tag v-if="record.businessStatus === '0'" color="cyan">
						草稿
					</a-tag>
					<a-tag v-if="record.businessStatus === '1'" color="blue">
						已过账
					</a-tag>
					<a-tag v-if="record.businessStatus === '2'" color="purple">
						已作废
					</a-tag>
				</template>
				<template v-if="column.dataIndex === 'businessShippingStoreIdName'">
					{{(record.businessSettlementType==='0' ? record.businessShippingStoreIdName : record.businessStorageStoreIdName) }}
				</template>

				<template v-if="column.dataIndex === 'action'">
					<a-space>
						<a @click="formRef.onOpen(record)" v-if="hasPerm('supplierFinanceSettlementEdit')">{{record.businessStatus === '0' ? '编辑' : '查看'}}</a>
						<a-divider type="vertical" v-show="record.businessStatus === '0'"
								   v-if="hasPerm(['supplierFinanceSettlementEdit', 'supplierFinanceSettlementDelete'], 'and')"/>
						<a-popconfirm title="确定要删除吗？" @confirm="deleteSupplierSettlement(record)">
							<a-button type="link" danger size="small" v-if="hasPerm('supplierFinanceSettlementDelete')" v-show="record.businessStatus === '0'">
								删除
							</a-button>
						</a-popconfirm>
					</a-space>
				</template>
			</template>
		</s-table>
	</a-card>
	<Form ref="formRef" @successful="tableRef.refresh()"/>
</template>

<script setup name="supplierFinanceSettlement">
import tool from '@/utils/tool'
import {cloneDeep} from 'lodash-es'
import {onMounted, ref} from "vue";
import Form from './form.vue'
import supplierSettlementApi from '@/api/supplier/finance/supplierSettlementApi'
import supplierBusinessMainApi from "@/api/supplier/business/supplierBusinessMainApi";
import supplierStoresApi from "@/api/supplier/base/supplierStoresApi";
import supplierAccountApi from "@/api/supplier/finance/supplierAccountApi";
import supplierSettlementProjectApi from "@/api/supplier/finance/supplierSettlementProjectApi";
import {message} from "ant-design-vue";
import downloadUtil from "@/utils/downloadUtil";
import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";

const searchFormState = ref({})
const searchFormRef = ref()
const tableRef = ref()
const formRef = ref()
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
// 查询区域显示更多控制
const advanced = ref(false)
const toggleAdvanced = () => {
	advanced.value = !advanced.value
}
const columns = ref([
	{
		title: '结算时间',
		dataIndex: 'createTime',
		sorter: true
	},
	{
		title: '门店',
		dataIndex: 'businessShippingStoreIdName'
	},
	{
		title: '结算类型',
		dataIndex: 'businessSettlementType',
		sorter: true
	},
	{
		title: '收（付）款账户',
		dataIndex: 'businessAccountIdName'
	},
	{
		title: '结算单号',
		dataIndex: 'businessCode',
		sorter: true
	},
	{
		title: '结算项目',
		dataIndex: 'businessProjectIdName'
	},
	{
		title: '结算对象',
		dataIndex: 'businessObjectIdName',
	},
	{
		title: '经办人ID',
		dataIndex: 'businessHandlerId',
		checked: false
	},

	{
		title: '结算金额',
		dataIndex: 'businessTotalAmount'
	},
	{
		title: '折让金额',
		dataIndex: 'businessDiscountAmount'
	},
	{
		title: '实收金额',
		dataIndex: 'businessInAmount'
	},
	{
		title: '实付金额',
		dataIndex: 'businessPayAmount'
	},
	{
		title: '结算前余额',
		dataIndex: 'businessAccountBalanceBefore',
		checked: false
	},
	{
		title: '结算后余额',
		dataIndex: 'businessAccountBalanceAfter',
		checked: false
	},
	{
		title: '结算状态',
		dataIndex: 'businessStatus'
	},
	{
		title: '摘要',
		dataIndex: 'businessAbstract',
		checked: false
	},
	{
		title: '备注',
		dataIndex: 'businessAbstract',
		checked: false
	}
])
// 操作栏通过权限判断是否显示
if (hasPerm(['supplierFinanceSettlementEdit', 'supplierFinanceSettlementDelete'])) {
	columns.value.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 150
	})
}
const selectedRowKeys = ref([])
// 列表选择配置
const options = {
	// columns数字类型字段加入 needTotal: true 可以勾选自动算账
	alert: {
		show: true,
		clear: () => {
			selectedRowKeys.value = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
const loadData = (parameter) => {
	const searchFormParam = cloneDeep(searchFormState.value)
	if (searchFormParam.createTime){
		searchFormParam.startCreateTime = searchFormParam.createTime[0]
		searchFormParam.endCreateTime = searchFormParam.createTime[1]
		delete searchFormParam.createTime
		return supplierSettlementApi.supplierSettlementPage(Object.assign(parameter, searchFormParam)).then((data) => {
			return data
		})
	}else{
		if (searchFormParam.createTime ===null){
			message.warn("请确定时间范围")
		}
		return Promise.resolve(null)
	}
}
//勾选汇总
const changeIsTotal = () => {
	searchFormState.value.isHavingByStore = false
	searchFormState.value.isHavingByAccount = false
	searchFormState.value.isHavingByProject = false
	searchFormState.value.isHavingByObject = false
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'createTime' || column.dataIndex === 'businessCode' || column.dataIndex === 'businessProjectIdName' || column.dataIndex === 'businessObjectIdName' || column.dataIndex === 'businessShippingStoreIdName' || column.dataIndex === 'businessAccountIdName' || column.dataIndex === "action"){
			column.checked = !searchFormState.value.isHavingByType
		}
	})
	columns.value = newColumns
	tableRef.value.refresh(true)
}
//更改汇总选项
const changeTotalOption = (options) => {
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(options === 'isHavingByStore' && column.dataIndex === 'businessShippingStoreIdName'){
			column.checked = searchFormState.value.isHavingByStore
		}
		if(options === 'isHavingByAccount' && column.dataIndex === 'businessAccountIdName'){
			column.checked = searchFormState.value.isHavingByAccount
		}
		if(options === 'isHavingByProject' && column.dataIndex === 'businessProjectIdName'){
			column.checked = searchFormState.value.isHavingByProject
		}
		if(options === 'isHavingByObject' && column.dataIndex === 'businessObjectIdName'){
			column.checked = searchFormState.value.isHavingByObject
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
onMounted(()=>{
	setDate('0')
	tableRef.value.refresh()
})

// 重置
const reset = () => {
	searchFormRef.value.resetFields()
	setDate('0')
	tableRef.value.refresh(true)
}
// 删除
const deleteSupplierSettlement = (record) => {
	let params = [
		{
			id: record.id
		}
	]
	supplierSettlementApi.supplierSettlementDelete(params).then(() => {
		tableRef.value.refresh(true)
	})
}
// 批量导出
const exportBatchSettlement = () => {
	if (selectedRowKeys.value.length > 0 && (searchFormState.value.isHavingByType === undefined || !searchFormState.value.isHavingByType)) {//只有当非汇总模式下才可导出选中的行
		const params = {
			startCreateTime: searchFormState.value.createTime[0],
			endCreateTime: searchFormState.value.createTime[1],
			isHavingByType:searchFormState.value.isHavingByType,
			ids: selectedRowKeys.value
				.map((m) => {
					return m
				})
				.join()
		}
		supplierSettlementApi.supplierSettlementExport(params).then((res)=>{
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
		return
	}
	const searchFormParam = cloneDeep(searchFormState.value)
	if (searchFormParam.createTime !==null ) {
		searchFormParam.startCreateTime = searchFormParam.createTime[0]
		searchFormParam.endCreateTime = searchFormParam.createTime[1]
		delete searchFormParam.createTime
		supplierSettlementApi.supplierSettlementExport(searchFormParam).then((res)=>{
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
	}else{
		message.warn("请确定时间范围")
	}
}
const projectOption = ref([])
const xnsettlementProjectIdPageSelectRef = ref();
const settlementProjectIdSelector = (param) => {
	return supplierSettlementProjectApi.supplierSettlementProjectPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.projectName,
					id: item.id,
					type: item.projectType
				};
			});
		}
		projectOption.value = [...projectOption.value, ...data.records]
		return Promise.resolve(data)
	})
}
const projectName = ref() //结算项目名称
const projectIdChange = (target) => {
	if(target){
		let index = projectOption.value.findIndex(function (project) {
			return project.id === target
		})
		projectName.value = projectOption.value[index].name
		if (projectName.value === '销售收入') {
			xnsettlementObjectIdPageSelectRef.value.onPage({current: 1, objectType: '1'})
		} else {
			if (projectName.value === '采购支出') {
				xnsettlementObjectIdPageSelectRef.value.onPage({current: 1, objectType: '0'})
			} else {
				xnsettlementObjectIdPageSelectRef.value.onPage({current: 1,objectType: null})
			}
		}
	}else{
		xnsettlementObjectIdPageSelectRef.value.onPage({current: 1,objectType: null})
	}
	searchFormState.value.settlementObjectId = null
}
const settlementTypeOptions = [{label:'收入', value:'0'}, {label:'支出', value:'1'}]
const businessSettlementTypeChange = (value) => {
	searchFormState.value.businessProjectId = null
	searchFormState.value.businessObjectId = null
	searchFormState.value.businessCode = null
	searchFormState.value.businessBusinessId = null
	if (value) {
		xnsettlementProjectIdPageSelectRef.value.onPage({current: 1, projectType: value});
	}else{
		console.log(value)
		xnsettlementProjectIdPageSelectRef.value.onPage({current: 1,projectType: null});
	}
}
const settlementStatusOptions = tool.dictList('BUSINESS_STATUS')
const xnsettlementObjectIdPageSelectRef = ref();
const settlementObjectIdSelector = (param) => {
	return supplierObjectsApi.supplierObjectsPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.objectName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const xnsettlementStoreIdPageSelectRef = ref();
const settlementStoreIdSelector = (param) => {
	return supplierStoresApi.supplierStoresPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.storeName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
const xnsettlementAccountIdPageSelectRef = ref();
const settlementAccountIdSelector = (param) => {
	return supplierAccountApi.supplierAccountPage(param).then((data) => {
		if (data.records) {
			data.records = data.records.map((item) => {
				return {
					name: item.accountName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
nextTick(() => {
	xnsettlementProjectIdPageSelectRef.value.onPage({current: 1});
	xnsettlementObjectIdPageSelectRef.value.onPage({current: 1});
	xnsettlementStoreIdPageSelectRef.value.onPage({current: 1});
	xnsettlementAccountIdPageSelectRef.value.onPage({current: 1});
});
const setDate = (index) => {
	switch (index) {
		case '0':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break

		case '1':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(Date.now() - 24 * 60 * 60 * 1000), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		case '2':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() + 1),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate() + 7
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '3':
			var dateArray = []
			dateArray[0] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay() - 6),
				'{y}-{m}-{d}'
			)
			dateArray[1] = tool.parseTime(
				new Date(
					new Date().getFullYear(),
					new Date().getMonth(),
					new Date(
						new Date().getFullYear(),
						new Date().getMonth(),
						new Date().getDate() - new Date().getDay()
					).getDate()
				),
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '4':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(
				new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1) - 1,
				'{y}-{m}-{d}'
			)
			searchFormState.value.createTime = dateArray
			break
		case '5':
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(new Date().getFullYear(), new Date().getMonth(), 1) - 1, '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
		default:
			var dateArray = []
			dateArray[0] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			dateArray[1] = tool.parseTime(new Date(), '{y}-{m}-{d}')
			searchFormState.value.createTime = dateArray
			break
	}
}
</script>
